package com.woniuxy.joylifeshop.controller;

import com.woniuxy.common.entity.*;
import com.woniuxy.common.utils.JWTUtils;
import com.woniuxy.joylifeshop.dto.ObjectDto;
import com.woniuxy.joylifeshop.exception.OrderException;
import com.woniuxy.joylifeshop.service.*;
import com.woniuxy.joylifeshop.vo.ResponseInformation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
public class OrderController {

    @Autowired
    CartService cartService;

    @Autowired
    CommodityService commodityService;

    @Autowired
    OrderService orderService;

    @Autowired
    MerchantService merchantService;

    @Autowired
    AddressService addressService;

    @Autowired
    MerchantCurrentAccountService merchantCurrentAccountService;

    @Autowired
    MerchantAccountService merchantAccountService;

    @Autowired
    MerchantIncomeService merchantIncomeService;

    @Autowired
    MerchantRepositoryService repositoryService;

    /**
     * @Author SooYoo
     * @Description 待发货改为待收货
     * @Param
     * @Return
     **/
    @RequestMapping("/receiverOrder")
    public ResponseInformation receiverOrder(String orderId){
        ResponseInformation responseInformation = new ResponseInformation();


        orderService.makereceiver(orderId);

        responseInformation.setMsg("修改成功");
        return responseInformation;
    }

    /**
    * @Author SooYoo
    * @Description 待发货改为待收货
    * @Param
    * @Return
    **/
    @RequestMapping("/postOrder")
    public ResponseInformation postOrder(String orderId){
        ResponseInformation responseInformation = new ResponseInformation();


        orderService.makepost(orderId);

        responseInformation.setMsg("修改成功");
        return responseInformation;
    }

    /**
    * @Author SooYoo
    * @Description 快速创建订单的方法
    * @Param
    * @Return
    **/
    @RequestMapping("/fastList")
    public ResponseInformation fastList(HttpServletRequest request,String shopId){
        String userId = JWTUtils.getUserId(request.getHeader("token"));
        System.out.println(shopId);
        ResponseInformation responseInformation = new ResponseInformation();

        try {
            //创建订单
            ShopOrder shopOrder =new ShopOrder();
            shopOrder.setOrderId(UUID.randomUUID().toString());
            shopOrder.setOrderDate(new Date());
            shopOrder.setStatus("未支付");
            shopOrder.setId(userId);
            //订单的价格
            ShopCommodity shopCommodity = commodityService.readCommodityByIdSimple(shopId);
            shopOrder.setTotal(shopCommodity.getPrice());
            //订单的地址
            shopOrder.setAddress("暂定");

            //创建订单的条目
            ShopOrderItem shopOrderItem = new ShopOrderItem();
            shopOrderItem.setItemId(UUID.randomUUID().toString());
            shopOrderItem.setComId(shopId);
            shopOrderItem.setOrderId(shopOrder.getOrderId());
            shopOrderItem.setCount(1L);
            shopOrderItem.setPrice(shopCommodity.getPrice());
            shopOrderItem.setSubtotal(shopCommodity.getPrice());
            shopOrderItem.setName(shopCommodity.getName());
            shopOrderItem.setMerchantId(shopCommodity.getMerchantId());

            responseInformation.setState(200);
            responseInformation.setMsg("快速创建订单成功");
            responseInformation.setData(shopOrder.getOrderId());

            List<ShopOrderItem> orderItems = new ArrayList<>();
            orderItems.add(shopOrderItem);
            //1.创建订单
            orderService.createOrder(shopOrder,orderItems);

            return responseInformation;

        } catch (Exception e) {
            e.printStackTrace();

            responseInformation.setMsg("失败");
            responseInformation.setState(500);

            return responseInformation;
        }

    }



    /**
    * @Author SooYoo
    * @Description 初始化订单详情页面的通用方法
    * @Param
    * @Return
    **/
    @RequestMapping("/initOrderDetail")
    public ResponseInformation initOrderDetail(String orderId,String userId){

        ResponseInformation responseInformation = new ResponseInformation();

        try {
            //根据用户id和订单号,查到订单对象和item对象集合
            ObjectDto objectDto = orderService.readOneOrderInfo(orderId);

            responseInformation.setMsg("查找成功");
            responseInformation.setState(200);
            responseInformation.setData(objectDto);

            return responseInformation;

        } catch (OrderException e) {
            e.printStackTrace();

            responseInformation.setState(500);
            responseInformation.setMsg("查找失败");

            return responseInformation;
        }
    }


    /**
    * @Author SooYoo
    * @Description
    * @Param
    * @Return
    **/
    @RequestMapping("initItem")
    public ResponseInformation initItem(HttpServletRequest request,String status){
        String userId = JWTUtils.getUserId(request.getHeader("token"));
        //System.out.println(status);
        ResponseInformation responseInformation = new ResponseInformation();

        try {
            //找到所有的未支付的订单
            List<ObjectDto> objectDtos = orderService.readAllNeedOrder(userId,status);

            responseInformation.setMsg("找到订单");
            responseInformation.setState(200);
            responseInformation.setData(objectDtos);

            return responseInformation;

        } catch (OrderException e) {
            e.printStackTrace();

            responseInformation.setState(500);
            responseInformation.setMsg("未找到订单");

            return responseInformation;
        }
    }


    /**
    * @Author SooYoo
    * @Description other的订单支付
    * @Param
    * @Return
    **/
    @RequestMapping("/payOtherOrder")
    public ResponseInformation payOtherOrder(String orderId,String addrId,HttpServletRequest request){
        String userId = JWTUtils.getUserId(request.getHeader("token"));
        //System.out.println(addrId);
        ResponseInformation responseInformation = new ResponseInformation();
        ObjectDto dto = orderService.readOneOrderInfo(orderId);
        List<ShopOrderItem> shopOrderItems = (List<ShopOrderItem>) dto.getData2();
        //1验证库存-------------
//        for (ShopOrderItem shopOrderItem:shopOrderItems){
//            ShopMerchantRepository shopMerchantRepository = repositoryService.cheakRepository(shopOrderItem.getComId());
//            if (shopMerchantRepository.getStock()<shopOrderItem.getCount()){
//                responseInformation.setMsg("有商品存储不够,请稍后再试");
//                return responseInformation;
//            }
//        }
        try {
            //找到addr对象
            ObjectDto objectDto = addressService.readOtherMapAddressAndAddressObject(addrId, userId);
            ShopAddress shopAddress = (ShopAddress) objectDto.getData2();
            //1.修改对象
            orderService.modifyUnPayOrder(shopAddress,orderId);



            //批量生成商家的流水对象
            for (ShopOrderItem shopOrderItem:shopOrderItems ){
                ShopMerchantCurrentAccount shopMerchantCurrentAccount = new ShopMerchantCurrentAccount();

                shopMerchantCurrentAccount.setCurrentId(UUID.randomUUID().toString());
                shopMerchantCurrentAccount.setMerchantId(shopOrderItem.getMerchantId());
                shopMerchantCurrentAccount.setNumber(shopOrderItem.getPrice());
                shopMerchantCurrentAccount.setCurrDate(new Date());
                shopMerchantCurrentAccount.setCurrentType("001");

                merchantCurrentAccountService.creatMerchantCurrentAccountObject(shopMerchantCurrentAccount);
                //6.增加销量
                commodityService.addSales(shopOrderItem.getComId(),shopOrderItem.getCount());
                //3.修改商家账户
                merchantAccountService.modifyByPurchase(shopOrderItem);
                //4.修改商家收入
                merchantIncomeService.modifyMerchantIncomeInformationByCondition(shopOrderItem);

            }



            responseInformation.setMsg("支付成功");
            responseInformation.setState(200);

            return responseInformation;
        } catch (Exception e) {
            e.printStackTrace();

            responseInformation.setState(500);
            responseInformation.setMsg("支付失败");

            return responseInformation;
        }
    }
    /**
    * @Author SooYoo
    * @Description 初始化支付默认的订单
    * @Param
    * @Return
    **/
//    @Transactional
    @RequestMapping("/payDefaultOrder")
    public ResponseInformation payDefaultOrder(HttpServletRequest request,String orderId){
        String userId = JWTUtils.getUserId(request.getHeader("token"));
        ResponseInformation responseInformation =new ResponseInformation();

        ObjectDto dto = orderService.readOneOrderInfo(orderId);
        List<ShopOrderItem> shopOrderItems = (List<ShopOrderItem>) dto.getData2();
        //1验证库存-------------
//        for (ShopOrderItem shopOrderItem:shopOrderItems){
//            ShopMerchantRepository shopMerchantRepository = repositoryService.cheakRepository(shopOrderItem.getComId());
//            if (shopMerchantRepository.getStock()<shopOrderItem.getCount()){
//                responseInformation.setMsg("有商品存储不够,请稍后再试");
//                return responseInformation;
//            }


        try {
            //2找到默认的地址
            ObjectDto objectDto = addressService.readDefaultAddress(userId);
            ShopAddress shopAddress = (ShopAddress) objectDto.getData2();


            //3.修改订单
            orderService.modifyUnPayOrder(shopAddress,orderId);


            for (ShopOrderItem shopOrderItem:shopOrderItems ){
                ShopMerchantCurrentAccount shopMerchantCurrentAccount = new ShopMerchantCurrentAccount();

                shopMerchantCurrentAccount.setCurrentId(UUID.randomUUID().toString());
                shopMerchantCurrentAccount.setMerchantId(shopOrderItem.getMerchantId());
                shopMerchantCurrentAccount.setNumber(shopOrderItem.getPrice());
                shopMerchantCurrentAccount.setCurrDate(new Date());
                shopMerchantCurrentAccount.setCurrentType("001");
                //4.批量生成商家的流水对象
                merchantCurrentAccountService.creatMerchantCurrentAccountObject(shopMerchantCurrentAccount);

                //5.增加销量
                commodityService.addSales(shopOrderItem.getComId(),shopOrderItem.getCount());

                //6.修改商家账户
                merchantAccountService.modifyByPurchase(shopOrderItem);
                //7.修改商家收入
                merchantIncomeService.modifyMerchantIncomeInformationByCondition(shopOrderItem);

            }


            responseInformation.setMsg("支付成功");
            responseInformation.setState(200);

            return responseInformation;
        } catch (Exception e) {
            e.printStackTrace();

            responseInformation.setState(500);
            responseInformation.setMsg("支付失败");

            return responseInformation;
        }

    }


    /**
    * @Author SooYoo
    * @Description 初始化订单确认页面
    * @Param
    * @Return
    **/
    @RequestMapping("/initOrder")
    public ResponseInformation initOrder(String orderId){

        ResponseInformation responseInformation = new ResponseInformation();

        try {
            //找到订单对象
            ObjectDto objectDto = orderService.readOneOrderInfo(orderId);
            //找到货物对象,商家对象,图片对象
            ObjectDto objectDto2 = merchantService.findMerchants((List<ShopOrderItem>) objectDto.getData2());

            responseInformation.setData(objectDto);
            responseInformation.setMsg("初始化订单成功");
            responseInformation.setState(200);
            responseInformation.setData2(objectDto2);

            return responseInformation;
        } catch (OrderException e) {
            e.printStackTrace();

            responseInformation.setState(500);
            responseInformation.setMsg("初始化订单失败");
            return responseInformation;
        }
    }



    /**
    * @Author SooYoo
    * @Description   创建一个订单
    * @Param
    * @Return
    **/
    @RequestMapping("/creatList")
    public ResponseInformation creatList(HttpServletRequest req){
        System.out.println("creatList");

        ResponseInformation responseInformation =  new ResponseInformation();

        try {
            //获取参数集合
            Map<String, String[]> parameterMap = req.getParameterMap();
            //找到用户id
            String userId = JWTUtils.getUserId(req.getHeader("token"));
            //String id = req.getParameter("id");
            //选中购物车id条目集合
            System.out.println(parameterMap.size());
            List<String> cartIdList = new ArrayList();
            for(int i=1;i<parameterMap.size()+1;i++) {
                System.out.println("cartId:  "+req.getParameter(""+i+""));
                cartIdList.add(req.getParameter(""+i+""));
            }
            System.out.println(cartIdList);
            //选中为空的情况,返回生成为空的消息
            if (parameterMap.size()==0){
                responseInformation.setMsg("当前订单为空");
                responseInformation.setState(502);
                return responseInformation;
            }else {
                //找到购物车条目对象集合
                List<ShopCart> shopCarts = cartService.readCartItemsByCartIdList(cartIdList);
                //构建order
                ShopOrder shopOrder = new ShopOrder();
                shopOrder.setOrderId(UUID.randomUUID().toString());
                shopOrder.setId(userId);
                shopOrder.setAddress("暂定");
                shopOrder.setStatus("未支付");
                shopOrder.setOrderDate(new Date());
                //计算总价
                Long total = 0L;
                for (int i=0 ; i<shopCarts.size();i++){
                    //找到价格
                    ShopCommodity shopCommodity = commodityService.readCommodityByIdSimple(shopCarts.get(i).getComId());
                    total = total + shopCommodity.getPrice()*shopCarts.get(i).getCount();
                }
                shopOrder.setTotal(total);
               //构建条目集合
                List<ShopOrderItem> shopOrderItems = new ArrayList<>();
                for (int i=0 ; i<shopCarts.size();i++){
                    ShopOrderItem shopOrderItem = new ShopOrderItem();
                    shopOrderItem.setItemId(UUID.randomUUID().toString());
                    shopOrderItem.setOrderId(shopOrder.getOrderId());
                    ShopCommodity shopCommodity = commodityService.readCommodityByIdSimple(shopCarts.get(i).getComId());
                    shopOrderItem.setComId(shopCommodity.getShopId());
                    shopOrderItem.setName(shopCommodity.getName());
                    shopOrderItem.setPrice(shopCommodity.getPrice());
                    shopOrderItem.setCount(shopCarts.get(i).getCount());
                    shopOrderItem.setSubtotal(shopCarts.get(i).getCount()*shopCommodity.getPrice());
                    shopOrderItem.setId(userId);
                    //添加item的商家id
                    shopOrderItem.setMerchantId(shopCommodity.getMerchantId());
                    shopOrderItems.add(shopOrderItem);
                }
                //删除购物车条目
                for (int i=0 ; i<shopCarts.size();i++){
                    cartService.removeCartItem(shopCarts.get(i).getCartId());
                }

                //1.创建订单
                orderService.createOrder(shopOrder,shopOrderItems);


                responseInformation.setData(shopOrder.getOrderId());
                responseInformation.setMsg("创建订单成功");
                responseInformation.setState(200);
                return responseInformation;

            }
        } catch (OrderException e) {
            e.printStackTrace();
            responseInformation.setMsg("创建订单失败");
            responseInformation.setState(500);
            return responseInformation;
        }
    }




}
